#ifndef CSIMPLETERRAIN_H
#define CSIMPLETERRAIN_H

#include "CEngine.h"

struct LineVertex
{
	D3DXVECTOR3 VPos;
	DWORD color;
	static const int FVF=D3DFVF_XYZ|D3DFVF_DIFFUSE;
};
struct TerrainVertex
{		
	D3DXVECTOR3 Position;
	D3DXVECTOR3 Normal;
	D3DXVECTOR3 Tangent;
	D3DXVECTOR3 Binormal;
	DWORD color;
	float tu,tv;
	float tu2,tv2;	
	static 	const int FVF = D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_NORMAL|D3DFVF_TEX2;
};
class CSimpleTerrain: public CSingleTon<CSimpleTerrain>
{
public:

	~CSimpleTerrain();
	CSimpleTerrain(){};

	bool SetupTerrain(int MapSize,int HeightScale,int MapScale,
		int TextureIncrement,int DetailIncrement,
		std::string HeightMapFile,std::string Texture,
		std::string DetailTexture);

	void LoadHeightMap(std::string HeightMapFile);
	void SmoothHeightMap(int Smooth);
	void SetupVertexBuffer();
	void SetupIndexBuffer();
	void ComputeNormals();
	void ComputeTangentBinormal();
	void SetSamplerState();
	void Render();
	void Render2();
	void Render3();
	void UpdateTerrain();

	int GetMapSize()       {return m_MapSize;}
	int GetHeightScale()   {return m_HeightScale;}
	int GetMapScale()      {return m_MapScale;}	
	int GetVertices()      {return NumVertices;}
	int GetTriangles()     {return NumTriangles;}

	float GetHeightMapEntry(int x,int z){
		return HeightMap[x+(m_MapSize*z)];
	}
	float GetScaledHeight(int x,int z)	{
		return HeightMap[x+(m_MapSize*z)]*m_HeightScale;
	}

	float GetTerrainHeight( float x, float z );
	float BilinearInterpolation(float iX, float iZ);
private:
	unsigned char    *HeightMap;
	TerrainVertex    *VertexData;
	DWORD            *IndexData;
	LineVertex       *m_LineVertex;

	LPDIRECT3DVERTEXBUFFER9 TerrainVb;
	LPDIRECT3DINDEXBUFFER9  TerrainIb;
	LPDIRECT3DTEXTURE9      TerrainTexture;
	LPDIRECT3DTEXTURE9      TerrainDetailTexture,blendmapTexture;
	LPD3DXEFFECT            TerrainEffect;
	IDirect3DVertexDeclaration9* vertexDecleration;

	int NumVertices;
	int NumTriangles;
	int m_MapSize;
	int m_MapScale;
	int m_HeightScale;
	int m_TextureIncrement;
	int m_DetailIncrement;	
	int depth;
	bool useshader;	
};
#endif